<?php

namespace App\Http\Controllers\Admin;

use App\Consts\CacheConst;
use App\Exceptions\ExceptionSms;
use App\Models\Admin;
use App\Models\AdminRole;
use App\Requests\Admin\StoreRequest;
use Carbon\Carbon;

/**
 * 账号管理
 * Class AccountController
 * @package App\Http\Controllers\Admin
 */
class AccountController extends CommonController
{
    // 主页
    public function index()
    {
        $search_forms = Admin::getForms(['user_name', 'real_name', 'mobile', 'role_id', 'is_enable']);
        $cols         = [[
            ['field' => 'user_name', 'title' => '用户名'],
            ['field' => 'real_name', 'title' => '姓名'],
            ['field' => 'mobile', 'title' => '手机号'],
            ['field' => 'role_name', 'title' => '角色'],
            ['field' => 'is_enable_format', 'title' => '状态', 'escape' => false],
            ['field' => 'last_login_at', 'title' => '登录时间'],
            ['field' => 'last_login_ip', 'title' => '登录IP'],
            ['field' => 'action', 'title' => '操作', 'escape' => false],
        ]];
        $uri          = '/admin/account/list';

        $permission_code = 'account-query';

        $top_btns = [
            ['code' => 'account-add'],
        ];
        return view('components.list', compact('cols', 'uri', 'top_btns', 'permission_code', 'search_forms'));
    }

    // 查询
    public function dataList()
    {
        $list = Admin::bgBaseQuery($this->input())->paginate($this->limit);
        foreach ($list as $item) {
            $item->role_name        = $item->role->name ?? "";
            $item->is_enable_format = $item->formatIsEnable($item->is_enable);
            if ($item->id > 1) {
                $item->action           = $item->setRowBtns(['account-edit', 'account-delete'], [
                    'account-enable'  => [
                        ['is_enable' => 0]
                    ],
                    'account-disable' => [
                        ['is_enable' => 1]
                    ]
                ]);
            } else {
                $item->action = '';
            }
        }
        return ExceptionSms::homeList($list->items(), $list->total());
    }

    // 表单
    public function editAdd()
    {
        $id = $this->input('id');

        $data = $id ? Admin::getOneById($id) : null;

        $save_forms = Admin::getForms(['avatar', 'user_name', 'real_name', 'mobile', 'role_id', 'remark', 'content']);

        $permission_code = $id ? 'account-edit-save' : 'account-add-save';

        return view('components.save_form', compact('data', 'save_forms', 'permission_code'));
    }

    // 存储
    public function dataSave(StoreRequest $request)
    {
        $id              = $request->id;
        $data            = $id ? Admin::getOneById($id) : new Admin();
        $data->user_name = $request->user_name;
        $data->real_name = $request->real_name;
        $data->mobile    = $request->mobile;
        $data->role_id   = $request->role_id;
        $data->save();
        return ExceptionSms::returnSuccess();
    }

    // 删除
    public function deletes()
    {
        $ids = $this->input('ids') ?? [];
        if (!is_array($ids)) ExceptionSms::returnError('请求参数错误');
        if (!collect($ids)->count()) ExceptionSms::returnError('请勾选数据');
        $adminId = \admin()->adminId();
        if (in_array($adminId, $ids)) ExceptionSms::returnError('不能删除自己');
        $admins = Admin::whereIn('id', $ids)->get();
        /** @var Admin $admin */
        foreach ($admins as $admin) {
            \Cache::delete(sprintf(CacheConst::ADMIN_PERMISSIONS, $admin->id));
        }
        Admin::whereIn('id', $ids)->update([
            'is_delete'  => 1,
            'updated_at' => Carbon::now()->toDateTimeString()
        ]);
        return ExceptionSms::returnSuccess();
    }

    // 启用
    public function enables()
    {
        $ids = $this->input('ids') ?? [];
        if (!is_array($ids)) ExceptionSms::returnError('请求参数错误');
        if (!collect($ids)->count()) ExceptionSms::returnError('请勾选数据');
        Admin::whereIn('id', $ids)->update([
            'is_enable'  => 1,
            'updated_at' => Carbon::now()->toDateTimeString()
        ]);
        return ExceptionSms::returnSuccess();
    }

    // 禁用
    public function disables()
    {
        $ids = $this->input('ids') ?? [];
        if (!is_array($ids)) ExceptionSms::returnError('请求参数错误');
        if (!collect($ids)->count()) ExceptionSms::returnError('请勾选数据');
        Admin::whereIn('id', $ids)->update([
            'is_enable'  => 0,
            'updated_at' => Carbon::now()->toDateTimeString()
        ]);
        return ExceptionSms::returnSuccess();
    }
}
